package src

import (
     "fmt"
	"net/http"
	"encoding/json"
)

type Person struct {
	Id int `json:"person_id"`
	Fio string `json:"fio"`
    Birthday string `json:"birthday"`
}

type Persons struct{
   Persons []Person `json:"persons"`
}

func (ps *Persons) fill(body []byte) {
	err := json.Unmarshal(body, ps)
	if err!=nil {
		panic("unmarchalling Persons error")
	}
}

func fsspGetPersonsHandler(w http.ResponseWriter, r *http.Request) {
	emp, _ := ParseParams(r)
		
	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	
	obj,_ := json.Marshal(Response{ session, 0, "", getPersons()})
	fmt.Fprint(w, string(obj))
}

func getPersons() (persons []interface{}){

   persons = append(persons,Person{1,"Navalny Alexey Anatolievich","04.06.1978"})
   persons = append(persons,Person{2,"Иванов И.И.","12.11.1960"})
   
   return    
}

func fsspUpdatePersonsHandler (w http.ResponseWriter, r *http.Request) {
	emp, body := ParseParams(r)
	var persons Persons
	persons.fill(body)
	
	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	
	var response Response
	if(len(persons.Persons)==0){
	   response = Response{ session, 1, "Передайте личности!", ""}
	} else {
	   response = Response{ session, 0, "", "OK"}
	}
	obj,_ := json.Marshal(response)
	fmt.Fprint(w, string(obj))  
}

type PersonIds struct {
  Ids []int `json:"persons_ids"`
}

func fsspDeletePersonsHandler (w http.ResponseWriter, r *http.Request) {
	emp, body := ParseParams(r)
	var pIds PersonIds
	err := json.Unmarshal(body, &pIds)
	if err!=nil {
		panic("unmarchalling PersonIds error")
	}
	
	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	
	var response Response
	if(len(pIds.Ids)==0){
	   response = Response{ session, 1, "Передайте идентификаторы!", ""}
	} else {
	   response = Response{ session, 0, "", "OK"}
	}
	obj,_ := json.Marshal(response)
	fmt.Fprint(w, string(obj))  
}

func fsspAddPersonsHandler (w http.ResponseWriter, r *http.Request) {
   	emp, body := ParseParams(r)
	var person Person
	err := json.Unmarshal(body, &person)
	if err!=nil {
		panic("unmarchalling PersonIds error")
	}
	
	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	
	var response Response
	if(len(person.Fio)==0){
	   response = Response{ session, 1, "Передайте ФИО!", ""}
	} else if (len(person.Birthday)==0){
	   response = Response{ session, 1, "Передайте birthday!", ""}	
	} else{
	   person.Id = 3
	   response = Response{ session, 0, "", person}
	}
	obj,_ := json.Marshal(response)
	fmt.Fprint(w, string(obj)) 
}
